package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeComputerResult;
import com.bidevalution.dao.entity.BeSectionMethod;
import com.bidevalution.dao.entity.BeSectionParameter;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.context.EvalutionMethodEnum;
import com.google.common.collect.Maps;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: 资格审查-资质、资格、许可证检查
 * @author: xiayf
 * 2020-04-13 夏云飞 bug(设计评定分离法也不检测人员)
 * @date: 2019-11-23 21:30
 */
public class EnterpriseQualificationCheckJob implements StepJobJdbcFactory {

    private JdbcTemplateService jdbcTemplateService;
    private Logger log = LogManager.getLogger(getClass());
    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layouCode) throws Exception {
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            BeSectionParameter beSectionParameter = jdbcTemplateService
                    .selectForObject("SELECT param_id,param_value FROM be_section_parameter WHERE section_id=:sectionId and param_id='enterpriseChecked'",
                            paramMap, BeanPropertyRowMapper.newInstance(BeSectionParameter.class));
            //判断接口数据获取完成标识 1表示获取完成(获取失败也算获取完成，不然提前计算任务一直未完成，推选完组长下一步下不去)
            if (beSectionParameter == null || !Constants.ONE.toString().equals(beSectionParameter.getParamValue())) {
                throw new Exception("企业资质资格接口数据还未获取完成，稍后计算");
            }
            StringBuilder sb = new StringBuilder();
            sb.append(" SELECT method_code FROM be_section_method WHERE section_id=:sectionId ");
            RowMapper<BeSectionMethod> beSectionMethodRm = BeanPropertyRowMapper.newInstance(BeSectionMethod.class);
            String methodCode = jdbcTemplateService.selectForObject(sb.toString(), paramMap, beSectionMethodRm).getMethodCode();
            sb.setLength(0);
            sb.append(" SELECT a.seq_id enterpriseId, CASE WHEN (c.EnterCheck='通过' ");
            //设计预审、设计后审和设计评定分离法不判断人员检查
            //2020-04-13 夏云飞 bug(设计评定分离法也不检测人员)
            if (!EvalutionMethodEnum.SJZH_ZGYS.getCode().equals(methodCode) && !EvalutionMethodEnum.SJZH_ZGHS.getCode().equals(methodCode)
                    && !EvalutionMethodEnum.SJPD.getCode().equals(methodCode)) {
                sb.append(" AND c.PersonCheck='通过' ");
            }
            sb.append(" ) OR c.ISCombo='1' THEN 0 ELSE 1 END errorCount ");
            sb.append(" FROM be_section_enterprise a ");
            sb.append(" LEFT JOIN be_section_info sec ON a.section_id=sec.seq_id ");
            sb.append(" LEFT JOIN be_enterprise_check c ON c.sectionCode=sec.section_code and INSTR(c.enterpriseName,CONCAT('、',a.enterprise_name,'、')) > 0 ");
            sb.append(" where a.section_id=:sectionId ");
            List<Map<String, Object>> enterList = jdbcTemplateService.selectForList(sb.toString(), paramMap);
            //保存计算结果
            saveResult(paramMap, enterList, beSectionStepJob);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****资格审查-资质、资格、许可证检查失败*****");
        }
    }

    private void saveResult(Map<String, Object> paramMap, List<Map<String, Object>> enterList,BeSectionStepJob beSectionStepJob) throws Exception {
        try {
            List<BeComputerResult> beComputerResultList = new ArrayList<>();
            BeComputerResult beComputerResult = null;
            for (Map<String, Object> dataMap : enterList) {
                beComputerResult = new BeComputerResult();
                beComputerResult.setSeqId(IdsUtil.uuid());
                beComputerResult.setSectionStepId(beSectionStepJob.getSectionStepId());
                beComputerResult.setSectionId(beSectionStepJob.getSectionId());
                beComputerResult.setEnterpriseId(OConvertUtils.getString(dataMap.get("enterpriseId")));
                //是否通过
                if (OConvertUtils.getInt(dataMap.get("errorCount")) > Constants.ZERO) {
                    beComputerResult.setIsPassed(Constants.ZERO.toString());
                } else {
                    beComputerResult.setIsPassed(Constants.ONE.toString());
                }
                beComputerResult.setCreateTime(DateUtil.now());
                beComputerResultList.add(beComputerResult);
            }
            SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(beComputerResultList);
            jdbcTemplateService.update(" DELETE FROM be_computer_result WHERE section_id=:sectionId AND section_step_id =:sectionStepId ", paramMap);
            jdbcTemplateService.bathInsert(" INSERT INTO be_computer_result(seq_id,section_step_id,section_id,enterprise_id,is_passed,create_time) " +
                    " VALUES(:seqId, :sectionStepId, :sectionId,:enterpriseId,:isPassed,:createTime) ", beanSources);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
}
